package com.share.finance.fund.schedule;

import com.share.config.redisson.RedisLock;
import com.share.finance.fund.service.ILoanInfoService;
import com.share.finance.fund.service.IRepaymentPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RePayMentSchedule {
    @Autowired
    private RedisLock redisLock;

    @Autowired
    private ILoanInfoService loanInfoService;

    @Autowired
    private IRepaymentPlanService iRepaymentPlanService;

    /**
     * 模拟放款 并  生成还款计划
     */
    @Scheduled(cron = "10 0/10 * * * ?")
    public void genLoanAndPlan() {
        final String LOCK_KEY = "fund:genLoanAndPlan";
        boolean locked = false;

        try {
            locked = redisLock.tryLock(LOCK_KEY, 3, TimeUnit.MINUTES);
            if (locked) {
                log.info("模拟放款 + 生成还款计划");
                loanInfoService.genLoanAndPlan();
            }
        } catch (Exception e) {
            log.error("模拟放款 + 生成还款计划 异常 ", e);
        } finally {
            if (locked) {
                redisLock.unlock(LOCK_KEY);
            }
        }
    }


    /**
     * 模拟 生成还款记录 并更新 还款计划
     */
    @Scheduled(cron = "30 5/15 * * * ?")
    public void genRepayRecord() {
        final String LOCK_KEY = "fund:genRepayRecord";
        boolean locked = false;

        try {
            locked = redisLock.tryLock(LOCK_KEY, 3, TimeUnit.MINUTES);
            if (locked) {
                log.info("模拟生成还款记录");
                iRepaymentPlanService.genRepayRecord();
            }
        } catch (Exception e) {
            log.error("模拟生成还款记录 异常 ", e);
        } finally {
            if (locked) {
                redisLock.unlock(LOCK_KEY);
            }
        }
    }


    /**
     * 计算逾期和罚息
     * 每天执行一次
     */
    @Scheduled(cron = "30 10 1 * * ?")
    public void callOverdueStatus() {
        final String LOCK_KEY = "fund:callOverStatus";
        boolean locked = false;

        try {
            locked = redisLock.tryLock(LOCK_KEY, 3, TimeUnit.MINUTES);
            if (locked) {
                log.info("模拟生成还款记录");
                iRepaymentPlanService.callOverdueStatus(null);
            }
        } catch (Exception e) {
            log.error("模拟生成还款记录 异常 ", e);
        } finally {
            if (locked) {
                redisLock.unlock(LOCK_KEY);
            }
        }
    }
}
